package cn.funnymap.lgis.tools.util.resttemplate;

import com.alibaba.fastjson2.JSONObject;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;

import java.net.URI;

/**
 * @author jiao xn
 */
@Component
public class RestTemplateUtil {
    private final RestTemplate restTemplate;

    public RestTemplateUtil(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    public JSONObject getForObject(String uri) {
        UriComponents uriComponents =
                UriComponentsBuilder.fromUriString(uri).build().expand("dodo").encode();
        URI queryUri = uriComponents.toUri();

        String responseBody = restTemplate.getForEntity(queryUri, String.class).getBody();
        return JSONObject.parseObject(responseBody);
    }

    public Document getForXml(String uri) throws DocumentException {
        UriComponents uriComponents =
                UriComponentsBuilder.fromUriString(uri).build().expand("dodo").encode();
        URI queryUri = uriComponents.toUri();

        String responseBody = restTemplate.getForEntity(queryUri, String.class).getBody();

        if (responseBody != null) {
            return DocumentHelper.parseText(responseBody);
        }

        return null;
    }
}
